"use client";
import { listQuestionBankByPageUsingPost } from "@/api/questionBankController";
import { deleteQuestionBankUsingPost } from "@/api/questionBankController";
import { PlusOutlined } from "@ant-design/icons";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { Button, message, Modal, Space, Typography } from "antd";
import { useRef, useState } from "react";
import CreateModal from "./components/createModal";
import UpdateModal from "./components/updateModal";

/**
 * 题库管理页面
 * @returns 题库管理页面
 */
const BanksAdminPage: React.FC = () => {
  const actionRef = useRef<ActionType>(undefined);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState({});
  const [messageApi, contextHolder] = message.useMessage();

  const columns: ProColumns<API.QuestionBank>[] = [
    {
      title: "题库名",
      dataIndex: "title",
      valueType: "text",
      search: true,
      ellipsis: true,
    },
    {
      title: "简介",
      dataIndex: "description",
      valueType: "textarea",
      ellipsis: true,
    },
    {
      title: "图片",
      dataIndex: "picture",
      valueType: "image",
      search: false,
      render: (_, entity) => (
        <img
          src={entity.picture}
          alt="题库"
          style={{ width: "46px", height: "46px" }}
        />
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      valueType: "dateTime",
      search: false,
      sorter: true,
      hideInForm: true,
    },
    {
      title: "更新时间",
      dataIndex: "editTime",
      valueType: "dateTime",
      search: false,
      sorter: true,
      hideInForm: true,
    },
    {
      title: "操作",
      dataIndex: "",
      search: false,
      hideInForm: true,
      render: (_, entity) => (
        <Space size="small">
          <Button
            type="link"
            onClick={() => {
              setCurrentRow(entity);
              setIsUpdateModalOpen(true);
            }}
          >
            修改
          </Button>
          <Typography.Link
            type="danger"
            onClick={() => {
              setCurrentRow(entity);
              setIsDeleteModalOpen(true);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];
  // 新增表单取消
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 新增表单提交
  const handleSubmit = () => {
    setIsModalOpen(false);
    actionRef.current?.reload();
  };
  // 修改表单取消
  const handleUpdateCancel = () => {
    setIsUpdateModalOpen(false);
  };
  // 修改表单提交
  const handleUpadateSubmit = () => {
    setIsUpdateModalOpen(false);
    actionRef.current?.reload();
  };
  const handleDelete = async (entity: API.QuestionBank) => {
    try {
      await deleteQuestionBankUsingPost({ id: entity.id });
      messageApi.success("删除成功");
      setIsDeleteModalOpen(false);
      actionRef.current?.reload();
    } catch (error) {
      messageApi.error("删除失败");
    }
  };
  return (
    <>
      {contextHolder}
      <ProTable<API.QuestionBank>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params, sort, filter) => {
          // const sortString = Object.entries(sort)
          //   .map(
          //     ([key, value]) => `${key},${value === "ascend" ? "asc" : "descend"}`
          //   )
          //   .join(",");
          try {
            const { code, data } = (await listQuestionBankByPageUsingPost({
              ...params,
              // sort: String(sort),
              ...filter,
            })) as API.QuestionBankQueryRequest as API.BaseResponsePageQuestionBank_;
            if (code === 0) {
              return {
                data: data?.records || [],
                total: Number(data?.total) || 0,
                success: true,
              };
            } else {
              return {
                data: [],
                total: 0,
                success: false,
              }; // 返回数据
            }
          } catch (e) {
            return {
              data: [],
              total: 0,
              success: false,
            }; // 返回数据
          }
        }}
        editable={{
          type: "multiple",
        }}
        columnsState={{
          persistenceKey: "pro-table-singe-demos",
          persistenceType: "localStorage",
          defaultValue: {
            option: { fixed: "right", disable: true },
          },
          onChange(value) {
            console.log("change", value);
          },
        }}
        rowKey="id"
        search={{
          labelWidth: "auto",
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        // form={{
        //   // Since transform is configured, the submitted parameters are different from the defined ones, so they need to be transformed here
        //   syncToUrl: (values, type) => {
        //     if (type === "get") {
        //       return {
        //         ...values,
        //         created_at: [values.startTime, values.endTime],
        //       };
        //     }
        //     return values;
        //   },
        // }}
        pagination={{
          pageSize: 10,
          // onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="题库管理"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setIsModalOpen(true);
              console.log("setIsModalOpen", isModalOpen);
            }}
            type="primary"
          >
            新增
          </Button>,
        ]}
      />
      <CreateModal
        isModalOpen={isModalOpen}
        columns={columns}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <UpdateModal
        isModalOpen={isUpdateModalOpen}
        columns={columns}
        oldData={currentRow}
        onCancel={handleUpdateCancel}
        onSubmit={handleUpadateSubmit}
      />
      <Modal
        title="提示"
        open={isDeleteModalOpen}
        onOk={() => handleDelete(currentRow)}
        onCancel={() => setIsDeleteModalOpen(false)}
      >
        <p>是否确认删除?</p>
      </Modal>
    </>
  );
};
export default BanksAdminPage;
